//! # 高级构建器模式示例
//! 
//! 展示如何使用AdvancedRustCloudBuilder构建复杂的微服务应用

use rustcloud::prelude::*;
use rustcloud::advanced_builder::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    tracing_subscriber::init();

    // 使用高级构建器创建框架
    let framework = AdvancedRustCloudBuilder::new("advanced-demo-service")
        // 基础配置
        .service(|s| {
            s.version = "2.0.0".to_string();
            s.description = Some("高级构建器演示服务".to_string());
            s.tags.insert("team".to_string(), "platform".to_string());
            s.tags.insert("version".to_string(), "v2".to_string());
        })
        // 网络配置
        .network(|n| {
            n.port = 8080;
            n.health_port = 8081;
            n.admin_port = Some(8888);
            n.bind_address = "0.0.0.0".to_string();
        })
        // 监控配置
        .monitoring(|m| {
            m.metrics.enabled = true;
            m.metrics.port = 9090;
            m.tracing.enabled = true;
            m.tracing.sampling_rate = 1.0;
            m.logging.level = "info".to_string();
        })
        // 组件配置
        .components(|c| {
            c.registry.registry_type = "nacos".to_string();
            c.registry.endpoints = vec!["127.0.0.1:8848".to_string()];
            c.load_balancer.strategy = "round_robin".to_string();
            c.circuit_breaker.enabled = true;
            c.proxy.enabled = true;
        })
        // 环境特定配置
        .for_development()
        // 条件配置
        .when(true, |builder| {
            builder.enable_gateway(8090)
                .add_route("/api/users", "user-service", vec!["GET".to_string(), "POST".to_string()])
                .add_route("/api/orders", "order-service", vec!["GET".to_string(), "POST".to_string()])
        })
        // 添加插件
        .use_plugin(Box::new(DatabasePlugin::new(
            "postgresql://localhost:5432/demo".to_string()
        )))
        .use_plugin(Box::new(RedisPlugin::new(
            "redis://localhost:6379".to_string()
        )))
        // 添加配置验证器
        .add_validator(Box::new(BasicConfigValidator))
        .add_validator(Box::new(CustomConfigValidator))
        // 添加环境适配器
        .add_environment_adapter(Box::new(DevelopmentAdapter))
        .add_environment_adapter(Box::new(ProductionAdapter))
        // 添加构建钩子
        .add_build_hook(Box::new(LoggingBuildHook))
        .add_build_hook(Box::new(MetricsBuildHook))
        // 从环境变量加载配置
        .load_from_env()?
        // 构建框架
        .build()
        .await?;

    println!("🚀 RustCloud框架启动成功!");
    println!("服务名称: {}", framework.get_config().service.name);
    println!("服务版本: {}", framework.get_config().service.version);
    println!("监听端口: {}", framework.get_config().network.port);
    println!("健康检查端口: {}", framework.get_config().network.health_port);

    // 启动框架
    framework.start().await?;

    // 运行健康检查
    match framework.health_check().await {
        Ok(health) => {
            println!("✅ 健康检查通过: {}", health.status);
            for (name, component) in &health.components {
                println!("  - {}: {}", name, component.status);
            }
        }
        Err(e) => {
            println!("❌ 健康检查失败: {}", e);
        }
    }

    // 服务发现演示
    if let Ok(instances) = framework.discover_services("user-service").await {
        println!("🔍 发现 user-service 实例: {} 个", instances.len());
        for instance in instances {
            println!("  - {}:{}:{}", instance.name, instance.host, instance.port);
        }
    }

    // 负载均衡演示
    if let Ok(Some(instance)) = framework.select_service_instance("user-service").await {
        println!("⚖️ 负载均衡选择实例: {}:{}", instance.host, instance.port);
    }

    // 模拟运行一段时间
    println!("🕐 服务运行中...");
    tokio::time::sleep(std::time::Duration::from_secs(5)).await;

    // 优雅关闭
    println!("🛑 正在停止服务...");
    framework.stop().await?;
    println!("✅ 服务已停止");

    Ok(())
}

/// 自定义配置验证器
struct CustomConfigValidator;

#[async_trait::async_trait]
impl ConfigValidator for CustomConfigValidator {
    async fn validate(&self, config: &RustCloudConfig) -> ServiceResult<()> {
        // 验证端口配置
        if config.network.port == config.network.health_port {
            return Err(ServiceError::ConfigError(
                "服务端口不能与健康检查端口相同".to_string()
            ));
        }

        // 验证注册中心配置
        if config.components.registry.endpoints.is_empty() {
            return Err(ServiceError::ConfigError(
                "注册中心地址不能为空".to_string()
            ));
        }

        // 验证监控配置
        if config.monitoring.metrics.enabled && config.monitoring.metrics.port == 0 {
            return Err(ServiceError::ConfigError(
                "启用指标收集时必须指定有效端口".to_string()
            ));
        }

        println!("✅ 自定义配置验证通过");
        Ok(())
    }

    fn name(&self) -> &str {
        "custom"
    }
}

/// 开发环境适配器
struct DevelopmentAdapter;

#[async_trait::async_trait]
impl EnvironmentAdapter for DevelopmentAdapter {
    async fn adapt(&self, config: &mut RustCloudConfig) -> ServiceResult<()> {
        // 开发环境优化配置
        config.monitoring.logging.level = "debug".to_string();
        config.monitoring.tracing.sampling_rate = 1.0; // 100%采样
        config.performance.connection_pool.max_connections = 50; // 减少连接数
        config.performance.thread_pool.max_threads = num_cpus::get() as u32; // 单倍CPU核数
        
        // 启用所有调试功能
        config.monitoring.metrics.enabled = true;
        config.monitoring.tracing.enabled = true;
        
        println!("🛠️ 开发环境配置适配完成");
        Ok(())
    }

    fn environment(&self) -> &str {
        "development"
    }
}

/// 日志构建钩子
struct LoggingBuildHook;

#[async_trait::async_trait]
impl BuildHook for LoggingBuildHook {
    async fn before_build(&self, builder: &AdvancedRustCloudBuilder) -> ServiceResult<()> {
        println!("📝 构建前日志初始化...");
        // 在这里可以进行日志系统的初始化
        Ok(())
    }

    async fn after_build(&self, framework: &RustCloudFramework) -> ServiceResult<()> {
        println!("📝 构建后日志配置完成");
        println!("   服务实例ID: {}", framework.get_service_instance().id);
        println!("   配置环境: {}", framework.get_config().service.environment);
        Ok(())
    }
}

/// 指标构建钩子
struct MetricsBuildHook;

#[async_trait::async_trait]
impl BuildHook for MetricsBuildHook {
    async fn before_build(&self, _builder: &AdvancedRustCloudBuilder) -> ServiceResult<()> {
        println!("📊 构建前指标系统准备...");
        Ok(())
    }

    async fn after_build(&self, framework: &RustCloudFramework) -> ServiceResult<()> {
        if framework.get_config().monitoring.metrics.enabled {
            println!("📊 指标收集已启用");
            println!("   指标端口: {}", framework.get_config().monitoring.metrics.port);
            
            // 可以在这里注册自定义指标
            if let Some(collector) = framework.get_metrics_collector() {
                println!("   指标收集器已就绪");
            }
        }
        Ok(())
    }
}